package linc.spring.demo.config;

import linc.spring.demo.bean.Role;
import linc.spring.demo.conversion.StringToRoleConverter;
import linc.spring.demo.editor.StringToRolePropertyEditor;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.context.support.ResourceBundleMessageSource;

import java.beans.PropertyEditor;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yqlin
 * @date 2021/9/6 23:12
 * @description
 */
@ComponentScan(basePackages = "linc.spring.demo")
public class ApplicationConfiguration {
    /**
     * 国际化
     */
    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n");
        messageSource.setDefaultEncoding("utf-8");
        return messageSource;
    }

    /**
     * 向Spring中注册PropertyEditor
     */
    @Bean
    public CustomEditorConfigurer customEditorConfigurer() {
        CustomEditorConfigurer configurer = new CustomEditorConfigurer();
        Map<Class<?>, Class<? extends PropertyEditor>> propertyEditorMap = new HashMap<>(2);
        // 表示StringToUserPropertyEditor可以将String转化成User类型，在Spring源码中，
        // 如果发现当前对象是String，而需要的类型是User，就会使用该PropertyEditor来做类型转化
        propertyEditorMap.put(Role.class, StringToRolePropertyEditor.class);
        configurer.setCustomEditors(propertyEditorMap);
        return configurer;
    }

    /**
     * Spring中注册ConversionService：
     */
    //    @Bean
    //    public ConversionServiceFactoryBean conversionServiceFactoryBean() {
    //        ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();
    //        factoryBean.setConverters(Collections.singleton(StringToRoleConverter.class));
    //        return factoryBean;
    //    }
}
